const { Controller } = require('egg');

const { homeRules } = require('../rules/home');

class HomeController extends Controller {
  async index() {
    console.log('HomeController index method called');

    const { ctx, service, app } = this;
    const { page_size = 10, page_num = 1, ...where } = ctx.request.query;

    const result = await service.home.findAll({
      page_size,
      page_num,
      where,
    });

    result.isErr
      ? app.emit('server.params.error', { ctx, error: result.error })
      : app.emit('req.success', { ctx, result });

    // console.log(ctx.app.config.sequelize);

    // console.log(Object.keys(ctx.model.Home.rawAttributes), 'rawAttributes');
    // ctx.body = users;
  }

  async show() {
    const { ctx, service } = this;
    const user = await service.Home.findByPk(ctx.params.id);
    ctx.body = user;
  }

  async create() {
    const { ctx, service } = this;

    const valid = ctx.validParams(homeRules.create, ctx.request.body);

    if (!valid) {
      const user = await service.Home.create(ctx.request.body);
      ctx.body = user;
    }
  }

  async update() {
    const { ctx, service } = this;

    const result = await service.Home.update(ctx.request.body, {
      where: {
        id: ctx.params.id,
      },
    });
    ctx.body = result;
  }

  async destroy() {
    const { ctx, service } = this;
    const result = await service.Home.destroy({
      where: {
        id: ctx.params.id,
      },
    });
    ctx.body = result;
  }
}

module.exports = HomeController;
